<script>
// import {onMounted, onUnmounted} from "vue";
import { h } from 'vue'
import AMapLoader from "@amap/amap-jsapi-loader";
import data from 'province-city-china/dist/level.json'
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";

export default {
  data() {
    return {
      index: -1,
      opeator: "",
      points: [],
      senderAddress: [],
      receiverAddress: [],
      options: data,
      Props: {
        label: 'name',
        value: 'name',
        children: 'children',
        checkStrictly: true,//是否父子联动
        emitPath: true// 是否在选中节点时展开子节点，默认值：true
      },
      vehicle: {
        id: "",//车辆id
        vehicleNumber: "",//车牌号
        vehicleType: "",//车辆类型
        capacity: 0,//单位：吨
      },
      driver: {
        id: "",//司机id
        name: "",//司机姓名
        phone: "",//司机电话
        licenseNumber: "",//驾驶证号
      },
      billVo: {
        totalCost: 0,//单位：元
        baseCost: 0,
        urgentFee: 0,
        refrigerationFee: 0,
        insuranceFee: 0,
        unitPrice: 0,
        distance: 0,//单位：公里
        totalWeight: 0,
        totalWorth: 0,//单位：元
      },
      dialogFormVisible: false,
      dialogFormVisible1: false,
      formLabelWidth: 120,
      goodsMsg: {
        goodsName: "",
        quantity: 0,
        unit: "",
        weight: 0,
        worth: 0,//单位：元
      },
      startIndex: 0,
      order: {
        vehicleTypeId: null,
        totalWorth: 0,//单位：元
        totalWeight: 0,//单位：吨
        vehicleId: null,//车牌号
        driverId: null,
        isRefrigerated: false,
        isUrgent: false,
        isInsurance: false,
        distance: 0,
        senderReceiver: {
          senderName: "",
          senderPhone: "",
          senderAddress: "",
          receiverName: "",
          receiverPhone: "",
          receiverAddress: "",
          receiverEmail: "liujunjiang.lio@foxmail.com"
        },
        orderItems: [
          {
            goodsName: "可口可乐",
            quantity: 1000,
            unit: "件",
            weight: 9,
            worth: 999.00
          },
          {
            goodsName: "雪碧",
            quantity: 2000,
            unit: "件",
            weight: 4,
            worth: 1999.00
          },
        ],
      },
      rules: {
        senderName: [
          { required: true, message: '请输入发货人姓名', trigger: 'blur' }
        ],
        senderPhone: [
          { required: true, message: '请输入发货人电话', trigger: 'blur' }
        ],
        receiverName: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        receiverPhone: [
          { required: true, message: '请输入收货人电话', trigger: 'blur' }
        ],
        receiverAddress: [
          { required: true, message: '请输入收货人地址', trigger: 'blur' }
        ],
        senderAddress: [
          { required: true, message: '请输入发货人地址', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //把地址封装成数组
    addressMethod() {
      let sender = ""
      let receiver = ""
      this.senderAddress.forEach((item) => {
        sender = sender + item
      })
      this.receiverAddress.forEach((item) => {
        receiver = receiver + item
      })
      this.order.senderReceiver.senderAddress = sender
      this.order.senderReceiver.receiverAddress = receiver
      this.points.push({ keyword: sender, city: this.senderAddress[0] })
      this.points.push({ keyword: receiver, city: this.receiverAddress[0] })
    },
    // 保存订单通过菜单路由把封装好的地址数组传递给订单跟踪页面
    saveOrder() {
      this.addressMethod()
      this.order.totalWeight = this.order.orderItems.reduce((a, b) => a + b.weight, 0)
      this.order.totalWorth = this.order.orderItems.reduce((a, b) => a + b.worth, 0)

      this.$axios.post("/order/add", this.order).then(
        res => {
          if (res.data.code === 200) {
            this.dialogFormVisible1 = false;
            ElMessage.success("添加成功")
          } else {
            ElMessage.error("添加失败")
          }
        }
      )
      // this.$router.push(
      //     {
      //       path: "/order/tracking",
      //       query: {item: JSON.stringify(this.points)}
      //     }
      // )
      // this.$axios.post("/order/add1", this.Order).then(
      //
      // )
    },
    // 打开添加货物信息弹窗
    openDialog() {
      this.opeator = "add"
      this.dialogFormVisible = true;
      this.goodsMsg = {}
    },
    // 添加货物信息
    addGoodsMsg() {
      if(this.opeator === "add"){
        this.dialogFormVisible = false;
        this.order.orderItems.push(this.goodsMsg)
        this.goodsMsg = {}
      }else{
        this.dialogFormVisible = false;
        this.order.orderItems[this.index] = this.goodsMsg
        this.goodsMsg = {}
      }
      this.opeator = ""
    },
    // 取消添加货物信息
    cancelAddGoodsMsg() {
      this.dialogFormVisible = false;
      this.goodsMsg = {}
    },
    // 删除货物信息
    deleteGoodsMsg(index, row) {
      this.order.orderItems.splice(index)//
    },
    // 编辑货物信息
    editGoodsMsg(index, row) {
      this.index = index;
      this.dialogFormVisible = true;
      this.goodsMsg = this.order.orderItems[this.index]
    },
    // 获取距离
    async getDistance() {
      return new Promise((resolve, reject) => {
        window._AMapSecurityConfig = {
          securityJsCode: 'a35977b0fe3c15cc97a39e8c0c684978',
        };

        AMapLoader.load({
          key: '1c522523b1358e4f0f15d2bec1071caa',  // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ["AMap.Scale", "AMap.CitySearch", "AMap.Driving", "AMap.AutoComplete"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
        }).then((AMap) => {
          const driving = new AMap.Driving({
            policy: 0, //驾车路线规划策略，0是速度优先的策略
          });

          let sender = "";
          let receiver = "";
          this.senderAddress.forEach((item) => {
            sender += item;
          });
          this.receiverAddress.forEach((item) => {
            receiver += item;
          });

          const points = [
            { keyword: sender, city: "" + this.senderAddress[0] },
            { keyword: receiver, city: "" + this.receiverAddress[0] },
          ];

          driving.search(points, function (status, result) {
            if (status === 'complete') {
              const distance = result.routes[0].distance / 1000;
              const formattedDistance = parseFloat(distance.toFixed(2));
              resolve(formattedDistance);
            } else {
              reject(new Error('获取驾车数据失败：' + result)); // 失败时抛出错误
            }
          });
        }).catch(reject);
      });
    },
    // 匹配司机与车辆加载中....
    async matching(formName) {
      this.addressMethod();
      this.$refs[formName].validate( async(valid) => {
        if (valid) {
          const loading = ElLoading.service({
        lock: true,
        text: '正在匹配司机与车辆以及生成账单...',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      this.order.distance = await this.getDistance()
      this.billVo.totalWorth = this.order.orderItems.reduce((a, b) => a + b.worth, 0)
      this.billVo.totalWeight = this.order.orderItems.reduce((a, b) => a + b.weight, 0)
      this.addressMethod();
      const condition = {
        isUrgent: this.order.isUrgent,
        isRefrigerated: this.order.isRefrigerated,
        isInsurance: this.order.isInsurance,
        distance: this.order.distance,
        totalWeight: this.billVo.totalWeight,
        totalWorth: this.billVo.totalWorth,
        senderAddress:this.order.senderReceiver.senderAddress
      }
      console.log("条件" + condition)
      this.$axios.post("/order/autoAllocation", condition).then((res) => {
        console.log("结果" + res.data.data)
        if (res.data.data !== null && res.data.data.billId == null) {
          this.vehicle.capacity = res.data.data.vehicle.capacity
          this.vehicle.vehicleType = res.data.data.vehicle.vehicleType.type
          this.vehicle.vehicleNumber = res.data.data.vehicle.vehicleNumber
          this.order.vehicleId = res.data.data.vehicle.id
          this.order.driverId = res.data.data.driver.id
          this.order.vehicleTypeId = res.data.data.vehicle.vehicleType.id
          this.driver.name = res.data.data.driver.name
          this.driver.phone = res.data.data.driver.phone
          this.driver.licenseNumber = res.data.data.driver.licenseNumber
          this.billVo.unitPrice = res.data.data.unitPrice
          this.billVo.insuranceFee = parseFloat((this.order.isInsurance ? this.billVo.totalWorth * 0.03 : 0).toFixed(2))
          this.billVo.urgentFee = parseFloat((this.order.isUrgent ? this.order.distance * res.data.data.unitPrice * 0.1 : 0).toFixed(2))
          this.billVo.refrigerationFee = parseFloat((this.order.isRefrigerated ? this.order.distance * res.data.data.unitPrice * 0.1 : 0).toFixed(2))
          this.billVo.baseCost = parseFloat((res.data.data.unitPrice * this.order.distance).toFixed(2))
          this.billVo.totalCost = parseFloat((this.billVo.baseCost + this.billVo.insuranceFee + this.billVo.urgentFee + this.billVo.refrigerationFee).toFixed(2))
          this.billVo.distance = this.order.distance
          this.dialogFormVisible1 = true;
          loading.close();
        }
        if (res.data.data !== null && res.data.data.billId != null) {
          ElMessageBox.alert('没有匹配到合适的司机和车辆，该订单已发布到平台', '提示', {
            confirmButtonText: '确定',
          }).then(() => {
            this.addressMethod()
            this.order.billId = res.data.data.billId
            this.order.vehicleId = res.data.data.vehicle.id
            this.order.totalWeight = this.order.orderItems.reduce((a, b) => a + b.weight, 0)
            this.order.totalWorth = this.order.orderItems.reduce((a, b) => a + b.worth, 0)
            this.$axios.post("/order/addOther", this.order).then(
              res => {
                if (res.data.code === 200) {
                  ElMessage.success("发布成功")
                } else {
                  ElMessage.error("发布失败")
                }
              }
            )
            this.dialogFormVisible1 = false;
          }).catch(() => {
            this.dialogFormVisible1 = false;
          });
          loading.close();
        }
        if (res.data.data == null) {
          ElMessageBox.alert('没有匹配到合适的司机和车辆，该订单已发布到平台', '提示', {
            confirmButtonText: '确定',
          }).then(() => {
            this.addressMethod()
            this.order.totalWeight = this.order.orderItems.reduce((a, b) => a + b.weight, 0)
            this.order.totalWorth = this.order.orderItems.reduce((a, b) => a + b.worth, 0)
            this.$axios.post("/order/addOther", this.order).then(
              res => {
                if (res.data.code === 200) {
                  ElMessage.success("发布成功")
                } else {
                  ElMessage.error("发布失败")
                }
              }
            )
            this.dialogFormVisible1 = false;
          }).catch(() => {
            this.dialogFormVisible1 = false;
          });
          loading.close();
        }
      }
      )
        }else{
          console.log("校验失败");
          return false;
        }
      })
    }
  }
}
</script>

<template>
  <!--  基本信息-->
  <div id="baseForm">
    <el-form :inline="true" :model="order" class="demo-form-inline">
      <h2>基础信息</h2>
      <el-row>
        <el-col :span="8">
          <el-form-item label="是否冷藏">
            <el-switch v-model="order.isRefrigerated" :active-value :inactive-value>
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否加急">
            <el-switch v-model="order.isUrgent" :active-value :inactive-value>
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否保价">
            <el-switch v-model="order.isInsurance" :active-value :inactive-value>
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <!--  发货人/收货人信息-->
  <div id="baseForm">
    <el-form :inline="true" :model="order.senderReceiver" class="demo-form-inline, demo-ruleForm" :rules="rules" ref="senderReceiver"
>
      <h2 style="padding-bottom: 5px">发货人收货人信息</h2>
      <el-row>
        <el-col :span="8">
          <el-form-item label="发货人姓名" prop="senderName">
            <el-input v-model="order.senderReceiver.senderName" placeholder="发货人姓名" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发货人电话" prop="senderPhone">
            <el-input v-model="order.senderReceiver.senderPhone" placeholder="发货人电话" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发货地址" prop="senderAddress">
            <el-cascader v-model="senderAddress" :options="options" :props="Props" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货人姓名" prop="receiverName">
            <el-input v-model="order.senderReceiver.receiverName" placeholder="收货人姓名" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货人电话" prop="receiverPhone">
            <el-input v-model="order.senderReceiver.receiverPhone" placeholder="收货人电话" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收货地址" prop="receiverAddress">
            <el-cascader v-model="receiverAddress" :options="options" :props="Props" clearable />
            <!--            <el-input v-model="Order.senderReceiver.receiverAddress" placeholder="收货地址" clearable/>-->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <!--  货物信息-->
  <div id="baseForm">
    <div style="display: flex; justify-content: space-between">
      <span>货物列表</span>
      <el-button link type="primary" size="small" @click="openDialog">添加</el-button>
    </div>
    <el-table :data="order.orderItems" style="width: 100%">
      <el-table-column prop="id" label="序号">
        <template v-slot="scope">
          {{ scope.$index + 1 + startIndex }} <!-- +1 是因为索引是从0开始的 -->
        </template>
      </el-table-column>
      <el-table-column prop="goodsName" label="货物名"></el-table-column>
      <el-table-column prop="quantity" label="数量"></el-table-column>
      <el-table-column prop="unit" label="单位"></el-table-column>
      <el-table-column prop="weight" label="重量/吨"></el-table-column>
      <el-table-column prop="worth" label="价值/元"></el-table-column>

      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="deleteGoodsMsg(scope.$index, scope.row)">
            删除
          </el-button>
          <el-button link type="primary" size="small" @click="editGoodsMsg(scope.$index, scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog title="货物信息" v-model="this.dialogFormVisible" class="dialog">
    <el-form :model="goodsMsg">
      <el-form-item label="货物名称" :label-width="formLabelWidth">
        <el-input v-model="goodsMsg.goodsName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="数量" :label-width="formLabelWidth">
        <el-input-number v-model="goodsMsg.quantity" autocomplete="off"></el-input-number>
      </el-form-item>
      <el-form-item label="单位" :label-width="formLabelWidth">
        <el-input v-model="goodsMsg.unit" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="重量" :label-width="formLabelWidth">
        <el-input-number v-model="goodsMsg.weight" autocomplete="off"></el-input-number>
      </el-form-item>
      <el-form-item label="价值" :label-width="formLabelWidth">
        <el-input-number v-model="goodsMsg.worth" autocomplete="off"></el-input-number>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelAddGoodsMsg">取 消</el-button>
      <el-button type="primary" @click="addGoodsMsg">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog title="匹配结果" v-model="this.dialogFormVisible1" class="dialog1">
    <div id="baseForm">
      <el-form :inline="true" :model="vehicle" class="demo-form-inline">
        <h2 style="padding-bottom: 5px">车辆信息</h2>
        <el-row>
          <el-col :span="8">
            <el-form-item label="车牌号">
              <el-input v-model="vehicle.vehicleNumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车辆类型">
              <el-input v-model="vehicle.vehicleType" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车辆载重/吨">
              <el-input v-model="vehicle.capacity" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div id="baseForm">
      <el-form :inline="true" :model="driver" class="demo-form-inline">
        <h2 style="padding-bottom: 5px">司机信息</h2>
        <el-row>
          <el-col :span="8">
            <el-form-item label="司机姓名">
              <el-input v-model="driver.name" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="司机电话">
              <el-input v-model="driver.phone" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="驾驶证号">
              <el-input v-model="driver.licenseNumber" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div id="baseForm">
      <el-form :inline="true" :model="billVo" class="demo-form-inline">
        <h2 style="padding-bottom: 5px">费用相关信息</h2>
        <el-row>
          <el-col :span="8">
            <el-form-item label="加急费用(元)">
              <el-input v-model="billVo.urgentFee" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="冷藏费用(元)">
              <el-input v-model="billVo.refrigerationFee" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保险费用(元)">
              <el-input v-model="billVo.insuranceFee" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="路程距离(km)">
              <el-input v-model="billVo.distance" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价(元/km)">
              <el-input v-model="billVo.unitPrice" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="基础费用(元)">
              <el-input v-model="billVo.baseCost" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="货物总重量(吨)">
              <el-input v-model="billVo.totalWeight" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货物总价值(元)">
              <el-input v-model="billVo.totalWorth" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计总费用(元)">
              <el-input v-model="billVo.totalCost" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer1">
      <el-button @click="this.dialogFormVisible1 = false">取 消</el-button>
      <el-button type="primary" @click="saveOrder">确 定</el-button>
    </div>
  </el-dialog>
  <div class="saveBtn">
    <el-button type="primary" @click="matching('senderReceiver')">保存</el-button>
  </div>
</template>
<style>
#baseForm {
  border: black 1px solid;
  box-shadow: 0 0 10px black;
  border-radius: 5px;
  padding: 50px;
  margin: 20px auto auto;
  width: 90%
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.saveBtn {
  padding-top: 20px;
  width: 100px;
  margin: 0 auto;
}

.dialog {
  position: absolute;
  top: 20%;
  left: 45%;
  width: 400px;

}

.dialog1 {
  position: absolute;
  top: 5%;
  left: 5%;
  width: 90%;
  height: 90%;
}

.dialog-footer1 {
  position: absolute;
  bottom: 10px;
  width: 300px;
  margin: 0 auto;
}
</style>
